import './MessageBody'

export default class CimManager {
    DATA_HEADER_LENGTH: number
    constructor() {
        this.DATA_HEADER_LENGTH = 1
    }

    getBindAccountData(account: string, userType: any) {
        let systemInfo: any = uni.getSystemInfoSync()
        let deviceId = systemInfo.deviceId
        if (!deviceId) {
            deviceId = this.generateUUID()
        }
        let body = {
            account: account,
            userType: userType,
            channel: systemInfo.platform,
            deviceId: deviceId,
            pushId: systemInfo.clientId,
            clientVersion: systemInfo.clientVersion,
            deviceModel: systemInfo.model
        }
        return this.getRequestData(0, body)
    }

    innerOnMessageReceived(e: any, callBack: any) {
        let data = new Uint8Array(e.data)
        let type = data[0]
        let body = data.subarray(this.DATA_HEADER_LENGTH, data.length)
        // 绑定用户
        if (type === 0) {
            console.log('绑定用户')
        }
        // 心跳检测
        else if (type === 1) {
            console.log('心跳检测')
        }
        // 聊天消息 || 阅读消息 || 断开连接
        else if ([2, 3, 4, 5, 6, 9, 10].indexOf(type) >= 0) {
        // @ts-ignore
            let message = proto.com.cf.im.socket.proto.MessageBody.deserializeBinary(body)
            callBack(message.toObject(false))
        }
    }

    getRequestData(model: any, data: any) {
        // @ts-ignore
        let body = new proto.com.cf.im.socket.proto.MessageBody()
        body.setModel(model)
        body.setTimestamp(new Date().getTime())
        body.setData(JSON.stringify(data))
        let params = body.serializeBinary()
        let protobuf = new Uint8Array(params.length)
        protobuf.set(params, 0)
        return protobuf
    }

    getHeartbeatResponseData() {
        // @ts-ignore
        let body = new proto.com.cf.im.socket.proto.MessageBody()
        body.setModel(1)
        body.setTimestamp(new Date().getTime())
        body.setData('心跳')
        let params = body.serializeBinary()
        let protobuf = new Uint8Array(params.length)
        protobuf.set(params, 0)
        return protobuf
    }

    generateUUID() {
        let d = new Date().getTime()
        let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            let r = (d + Math.random() * 16) % 16 | 0
            d = Math.floor(d / 16)
            return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16)
        })
        return uuid.replace(/-/g, '')
    }
}
